package com.example.havi.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.havi.R;
import com.example.havi.adapter.ChatMessageAdapter;
import com.example.havi.adapter.EmojiAdapter;
import com.example.havi.adapter.MoreMenusAdapter;
import com.example.havi.bean.EmojiBean;
import com.example.havi.bean.HyChatUser;
import com.example.havi.bean.MessageBean;
import com.example.havi.bean.MoreMenuBean;
import com.example.havi.helper.ChatHelper;
import com.example.havi.helper.EmojiDataHelper;
import com.example.havi.helper.VoicePlayerHelper;
import com.example.havi.interfaces.HyphenateLibraryCallBack;
import com.example.havi.ui.chatitem.BaseChatViewHolder;
import com.example.havi.ui.voiceRecorder.RecorderVoiceView;
import com.example.havi.util.ChatToastUtil;
import com.example.havi.util.GlideEngine;
import com.example.havi.util.GsonUtils;
import com.example.havi.util.InputMethodUtils;
import com.example.havi.util.LogUtil;
import com.example.havi.util.StatusBarUtil;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.NetUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ChatActivity extends AppCompatActivity implements View.OnClickListener, ChatMessageAdapter.OnItemViewClickListener, EMMessageListener, VoicePlayerHelper.UpdateVoiceItemListener {

    TextView backIv;
    RecyclerView recyclerView;
    SwipeRefreshLayout swipeRefresh;
    ImageView chatVoiceIv;
    EditText contentEt;
    ImageView chatEmojiIv;
    ImageView chatMoreIv;
    TextView title_tv;
    RecorderVoiceView recorderVoiceView;
    private RecyclerView emojiRecyclerView, moreRecyclerView;
    private String toChatUserId;
    private ChatMessageAdapter chatMessageAdapter;
    private EMConversation conversation;
    private int pageSize = 20;

    private Handler handler = new Handler();
    private boolean isGroupChat;
    private EMConversation.EMConversationType chatType;
    private int pagesize = 20;
    private HyChatUser hyChatUser;
    private HyphenateLibraryCallBack libraryCallBack;

    private String toUserId;
    private String toUserAvatar;
    private String toUserNickName;

    private String toGroupId;
    private String toGroupName;
    private String toGroupImg;
    private RelativeLayout takePhone;
    private String isService;
    private MyConnectionListener myConnectionListener;


    /**
     *
     * @param context
     * @param toUserId  用户id
     * @param toUserAvatar  用户头像
     * @param toUserNickName    用户昵称
     * @param toChatUserId   用户聊天id
     * @param isService   判断是否为客服
     */
    public static void startActivity(Context context, String toUserId,String toUserNickName,String toUserAvatar,String toChatUserId,String isService) {
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra("toUserId", toUserId);
        intent.putExtra("toUserAvatar", toUserAvatar);
        intent.putExtra("toUserNickName", toUserNickName);
        intent.putExtra("toChatUserId", toChatUserId);
        intent.putExtra("isService",isService);
        context.startActivity(intent);
    }

    /**
     *
     * @param context
     * @param toGroupId     群的id
     * @param toGroupName   群名称
     * @param toGroupImg    群头像
     * @param toChatUserId    群的聊天id
     */
    public static void startActivityGroup(Context context,String toGroupId,String toGroupName,String toGroupImg,String toChatUserId) {
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra("toGroupId", toGroupId);
        intent.putExtra("toGroupName", toGroupName);
        intent.putExtra("toGroupImg", toGroupImg);
        intent.putExtra("toChatUserId", toChatUserId);
        intent.putExtra("isGroupChat", true);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#F2F3F4"), true);

        isGroupChat = getIntent().getBooleanExtra("isGroupChat", false);
        toChatUserId = getIntent().getStringExtra("toChatUserId");

        //单聊
        toUserId = getIntent().getStringExtra("toUserId");
        toUserAvatar = getIntent().getStringExtra("toUserAvatar");
        toUserNickName = getIntent().getStringExtra("toUserNickName");

        //群聊
        toGroupId = getIntent().getStringExtra("toGroupId");
        toGroupName = getIntent().getStringExtra("toGroupName");
        toGroupImg = getIntent().getStringExtra("toGroupImg");

        // 是否为客服
        isService = getIntent().getStringExtra("isService");

        if (isGroupChat) {
            chatType = EMConversation.EMConversationType.GroupChat;
        } else {
            chatType = EMConversation.EMConversationType.Chat;
        }
        //主项目交互
        libraryCallBack = ChatHelper.getInstance().getLibraryCallBack();
        conversation = EMClient.getInstance().chatManager().getConversation(toChatUserId, chatType, true);
        hyChatUser = ChatHelper.getInstance().getHyChatUser();
        findView();
        initView();
        initListener();
        //注册一个监听连接状态的listener
        myConnectionListener = new MyConnectionListener();
        EMClient.getInstance().addConnectionListener(myConnectionListener);

    }

    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
            LogUtil.e("zjw_zjw","main onConnected=");
        }
        @Override
        public void onDisconnected(final int error) {
            LogUtil.e("zjw_zjw","amin onDisconnected="+error);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(error == EMError.USER_REMOVED){
                        // 显示帐号已经被移除
                        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(ChatActivity.this);
                        builder.setTitle("警告");
                        builder.setMessage("另一台设备正在登陆！！");
                        builder.setCancelable(false);
                        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                finish();
                            }
                        });
                        builder.show();
                    }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(ChatActivity.this);
                        builder.setTitle("警告");
                        builder.setMessage("另一台设备正在登陆！！");
                        builder.setCancelable(false);
                        builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                               InputMethodUtils.hideSoftInput(ChatActivity.this);
                                finish();
                            }
                        });
                        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {

                            }
                        });
                        builder.show();
                    } else {
                        if (NetUtils.hasNetwork(ChatActivity.this)){
                            ChatToastUtil.showToast(getBaseContext(),"连接不到聊天服务器");
                            //连接不到聊天服务器
                        }else{
                            //当前网络不可用，请检查网络设置
                            ChatToastUtil.showToast(getBaseContext(),"当前网络不可用，请检查网络设置");
                        }
                    }
                }
            });
        }
    }
    private void findView() {
        backIv = findViewById(R.id.back_tv);
        title_tv = findViewById(R.id.title_tv);
        recyclerView = findViewById(R.id.recyclerView);
        swipeRefresh = findViewById(R.id.swipeRefresh);
        chatVoiceIv = findViewById(R.id.chat_voice_iv);
        contentEt = findViewById(R.id.content_et);
        chatEmojiIv = findViewById(R.id.chat_emoji_iv);
        chatMoreIv = findViewById(R.id.chat_more_iv);
        recorderVoiceView = findViewById(R.id.recorderVoiceViewLayout);
        emojiRecyclerView = findViewById(R.id.emojiRecyclerView);
        moreRecyclerView = findViewById(R.id.moreRecyclerView);
        contentEt.setHorizontallyScrolling(false);
        contentEt.setMaxLines(Integer.MAX_VALUE);
        takePhone = findViewById(R.id.rl_take_phone);  // 添加拨打电话界面
    }

    public void initView() {
        initConversation();
        initEmoji();
        initMoreMenu();
        VoicePlayerHelper.INSTANCE.init(this,this); //初始化语音播放帮助类

        // 扩展一键拨打电话
        if (isService.equals("0"))
        {
            takePhone.setVisibility(View.GONE);
        }else
        {
            takePhone.setVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        backIv.setOnClickListener(this);
        chatVoiceIv.setOnClickListener(this);
        chatEmojiIv.setOnClickListener(this);
        chatMoreIv.setOnClickListener(this);
        recorderVoiceView.setVoiceRecorderCallback(new RecorderVoiceView.VoiceRecorderCallback() {
            @Override
            public void onVoiceRecordComplete(String voiceFilePath, int voiceTimeLength) {
                sendVoiceMessage(voiceFilePath, voiceTimeLength * 1000);
            }
        });
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                InputMethodUtils.hideSoftInput(contentEt);
                recorderVoiceView.setVisibility(View.GONE);
                emojiRecyclerView.setVisibility(View.GONE);
                moreRecyclerView.setVisibility(View.GONE);
                return false;
            }
        });
        contentEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (keyEvent != null && keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    sendTextMessage(contentEt.getText().toString());
                    contentEt.setText("");
                    return true;
                } else {
                    return false;
                }
            }
        });
        contentEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    recorderVoiceView.setVisibility(View.GONE);
                    emojiRecyclerView.setVisibility(View.GONE);
                    moreRecyclerView.setVisibility(View.GONE);
                }
            }
        });
        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                loadMoreMessage();
            }
        });

        // 拨打电话操作
        takePhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                /**
                 * 拨打电话（直接拨打电话）
                 *
                 * @param phoneNum 电话号码
                 */

                   call(isService);
            }
        });
    }


    private void initConversation() {
        LinearLayoutManager manager;
        recyclerView.setLayoutManager(manager = new LinearLayoutManager(getBaseContext()));
        ((SimpleItemAnimator)recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        manager.setStackFromEnd(true);
        recyclerView.setAdapter(chatMessageAdapter = new ChatMessageAdapter(getBaseContext()));
        chatMessageAdapter.setOnItemViewClickListener(this);

        initFetchHistoryMessage();  //消息分页获取初始化
        refreshData();
        refreshTitle();
    }

    /**
     * 显示标题
     */
    private void refreshTitle() {
        if (isGroupChat) {
            title_tv.setText(toGroupName+"");
        } else {
            title_tv.setText(toUserNickName+"");
        }

    }

    /**
     * 刷新列表数据
     */
    private void refreshData() {
        java.util.List<EMMessage> var = conversation.getAllMessages();
        conversation.markAllMessagesAsRead();
        chatMessageAdapter.updateData(Arrays.asList(var.toArray(new EMMessage[var.size()])));
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerView.scrollToPosition(chatMessageAdapter.getAllData().size() - 1);
            }
        }, 200);


    }

    /**
     * 初始化分页数据
     */
    private void initFetchHistoryMessage() {
//        try {
//            EMClient.getInstance().chatManager().fetchHistoryMessages(toChatUserId, chatType, pagesize, "");
        final List<EMMessage> msgs = conversation.getAllMessages();
        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            conversation.loadMoreMsgFromDB(msgId, pagesize - msgCount);
        }
//        } catch (HyphenateException e) {
//            e.printStackTrace();
//        }
    }

    boolean haveMoreData = true;

    private void loadMoreMessage() {
        if (!haveMoreData) {
            swipeRefresh.setRefreshing(false);
            return;
        }
        final List<EMMessage> messages;
        try {
            messages = conversation.loadMoreMsgFromDB(conversation.getAllMessages().size() == 0 ? "" : conversation.getAllMessages().get(0).getMsgId(), pageSize);
        } catch (Exception e1) {
            swipeRefresh.setRefreshing(false);
            return;
        }
        if (messages.size() > 0) {
            chatMessageAdapter.addData(messages);
            recyclerView.scrollToPosition(messages.size() - 1);
            if (messages.size() != pageSize) {
                haveMoreData = false;
            }
        } else {
            haveMoreData = false;
        }
        swipeRefresh.setRefreshing(false);
    }


    private void initMoreMenu() {
        List<MoreMenuBean> menus = new ArrayList<>();
        menus.add(new MoreMenuBean(0, R.drawable.photo_select_icon, "照片"));
        menus.add(new MoreMenuBean(1, R.drawable.take_photo_icon, "拍照"));
        moreRecyclerView.setLayoutManager(new GridLayoutManager(getBaseContext(), 4));
        MoreMenusAdapter adapter;
        moreRecyclerView.setAdapter(adapter = new MoreMenusAdapter(getBaseContext(), menus));
        adapter.setOnItemClickListener(new MoreMenusAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, MoreMenuBean bean) {
                switch (bean.getId()) {
                    case 0: //照片
                        PictureSelector.create(ChatActivity.this)
                                .openGallery(PictureMimeType.ofImage())
                                .imageSpanCount(3)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .isCamera(true)
                                .compress(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case 1: //拍照
                        PictureSelector.create(ChatActivity.this)
                                .openCamera(PictureMimeType.ofImage())
                                .compress(true)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
                    if (localMedias != null && localMedias.size() > 0) {
                        sendImageMessage(localMedias);
                    }
                    break;
            }
        }
    }

    private void sendTextMessage(String content) {
        if (TextUtils.isEmpty(content.trim())) {
            ChatToastUtil.showToast(getBaseContext(), "不能发送空消息");
            return;
        }
        EMMessage message = EMMessage.createTxtSendMessage(content, toChatUserId);
        sendMessage(message);
    }

    private void sendImageMessage(List<LocalMedia> localMedias) {
        EMMessage message = EMMessage.createImageSendMessage(localMedias.get(0).getCompressPath(), true, toChatUserId);
        sendMessage(message);
    }

    private void sendVoiceMessage(String voiceFilePath, int length) {
        EMMessage message = EMMessage.createVoiceSendMessage(voiceFilePath, length, toChatUserId);
        sendMessage(message);
    }

    private void sendMessage(EMMessage message) {
        if (message == null) {
            return;
        }
        MessageBean messageBean = new MessageBean();
        //自己信息
        messageBean.setUserId(hyChatUser.getUserId());
        messageBean.setChatId(hyChatUser.getChatId());
        messageBean.setAvatar(hyChatUser.getAvatar());
        messageBean.setNickName(hyChatUser.getNickName());

        if (isGroupChat) {   //群聊
            message.setChatType(EMMessage.ChatType.GroupChat);
            messageBean.setGroupName(toGroupName);
            messageBean.setGroupAvatar(toGroupImg);
        }else{//单聊
            //对方信息
            messageBean.setToAvatar(toUserAvatar);
            messageBean.setToNickName(toUserNickName);
            messageBean.setToUserId(toUserId);
        }
        String ext = GsonUtils.serializedToJson(messageBean);
        message.setAttribute("ext",ext);
        message.setMessageStatusCallback(messageStatusCallback);
        EMClient.getInstance().chatManager().sendMessage(message);
        refreshData();  //刷新数据
        LogUtil.e("frank", "发送聊天消息："
                + "\n ext = " + ext
                + "\n ChatType = " + message.getChatType()
                + "\n messageBody = " + message.getBody()
                + "\n messageForm = " + message.getFrom()
                + "\n messageTo = " + message.getTo());
    }




      private void initEmoji() {
        final List<EmojiBean> emojis = EmojiDataHelper.getEmojiData();
        emojiRecyclerView.setLayoutManager(new GridLayoutManager(getBaseContext(), 7));
        EmojiAdapter adapter;
        emojiRecyclerView.setAdapter(adapter = new EmojiAdapter(getBaseContext(), emojis));
        adapter.setOnItemClickListener(new EmojiAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, EmojiBean bean) {
                contentEt.append(bean.getEmojiStringByUnicode());
            }
        });
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.back_tv) {
            finish();
        } else if (i == R.id.chat_voice_iv) {
            AndPermission.with(this)
                    .runtime()
                    .permission(Permission.Group.MICROPHONE, Permission.Group.STORAGE)
                    .onGranted(new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> data) {
                            contentEt.clearFocus();
                            InputMethodUtils.hideSoftInput(contentEt);
                            recorderVoiceView.setVisibility(recorderVoiceView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                            emojiRecyclerView.setVisibility(View.GONE);
                            moreRecyclerView.setVisibility(View.GONE);
                        }
                    })
                    .onDenied(new Action<List<String>>() {
                        @Override
                        public void onAction(List<String> data) {

                        }
                    })
                    .start();


        } else if (i == R.id.chat_emoji_iv) {
            contentEt.clearFocus();
            InputMethodUtils.hideSoftInput(contentEt);
            emojiRecyclerView.setVisibility(emojiRecyclerView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
            recorderVoiceView.setVisibility(View.GONE);
            moreRecyclerView.setVisibility(View.GONE);

        } else if (i == R.id.chat_more_iv) {
            contentEt.clearFocus();
            InputMethodUtils.hideSoftInput(contentEt);
            moreRecyclerView.setVisibility(moreRecyclerView.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
            recorderVoiceView.setVisibility(View.GONE);
            emojiRecyclerView.setVisibility(View.GONE);
        }
    }

    //
    @Override
    public void onItemViewClick(BaseChatViewHolder viewHolder, View view, int viewType, final int position, final EMMessage emMessage) {
        switch (viewType) {
            case 0: //bubble 气泡点击
                bubbleClick(emMessage);
                break;
            case 1://头像点击
                try {
                    //基本信息 头像等信息 通过扩展字段 ext传递
                    String ext = emMessage.getStringAttribute("ext");
                    MessageBean messageBean = GsonUtils.jsonToBean(ext, MessageBean.class);
                    libraryCallBack.goUserHome(ChatActivity.this,messageBean.getUserId());
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                break;
            case 2: //重发发送消息
                if(isFinishing()){
                    return;
                }
                new EaseAlertDialog(ChatActivity.this, R.string.resend, R.string.confirm_resend, null, new EaseAlertDialog.AlertDialogUser() {
                    @Override
                    public void onResult(boolean confirmed, Bundle bundle) {
                        if (!confirmed) {
                            return;
                        }
                        emMessage.setStatus(EMMessage.Status.CREATE);
                        chatMessageAdapter.notifyItemChanged(position);
                        emMessage.setMessageStatusCallback(new EMCallBack() {
                            @Override
                            public void onSuccess() {
                                notifyItemChanged(position);
                            }

                            @Override
                            public void onError(int i, String s) {
                                notifyItemChanged(position);
                            }

                            @Override
                            public void onProgress(int i, String s) {
                                notifyItemChanged(position);
                            }
                        });
                        sendMessage(emMessage);
                    }
                }, true).show();
                break;

        }
    }

    private void notifyItemChanged(final int position) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                chatMessageAdapter.notifyItemChanged(position);
            }
        });
    }

    private void bubbleClick(EMMessage emMessage) {
        switch (emMessage.getType()) {
            case TXT:
                break;
            case IMAGE:
                EMImageMessageBody body = (EMImageMessageBody) emMessage.getBody();
                String remoteUrl = body.getRemoteUrl();
                List<LocalMedia> medias = new ArrayList<>();
                LocalMedia localMedia = new LocalMedia();
                localMedia.setPath(remoteUrl);
                medias.add(localMedia);
                PictureSelector.create(ChatActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(0, medias);
                break;
            case VOICE:
                VoicePlayerHelper.INSTANCE.onVoiceItemClick(emMessage);
                break;
            case VIDEO:
                break;
            case LOCATION:
                break;
            case FILE:
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        VoicePlayerHelper.INSTANCE.onStop();
    }

    protected EMCallBack messageStatusCallback = new EMCallBack() {
        @Override
        public void onSuccess() {
            notifyDataSetChanged();

        }

        @Override
        public void onError(int code, String error) {
            notifyDataSetChanged();
        }

        @Override
        public void onProgress(int progress, String status) {
            notifyDataSetChanged();
        }
    };

    //消息接收--------------------------------------------------------------------------------start

    @Override
    protected void onResume() {
        super.onResume();
        EMClient.getInstance().chatManager().addMessageListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EMClient.getInstance().chatManager().removeMessageListener(this);
        EMClient.getInstance().removeConnectionListener(myConnectionListener);
    }

    @Override
    public void onMessageReceived(List<EMMessage> messages) {
        for (EMMessage message : messages) {
            String username = null;
            // group message
            if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                username = message.getTo();
            } else {
                // single chat message
                username = message.getFrom();
            }
            // if the message is for current conversation
            if (username.equals(toChatUserId) || message.getTo().equals(toChatUserId) || message.conversationId().equals(toChatUserId)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshData();
                    }
                });
                conversation.markMessageAsRead(message.getMsgId());
            }
        }
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {

    }

    @Override
    public void onMessageRead(List<EMMessage> list) {
        notifyDataSetChanged();
    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {
        notifyDataSetChanged();
    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {
        notifyDataSetChanged();
    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {
        notifyDataSetChanged();
    }

    private void notifyDataSetChanged() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                chatMessageAdapter.notifyDataSetChanged();
            }
        });
    }

    //语音播放帮助类 回调
    @Override
    public void onUpdateVoiceItem(EMMessage msg) {
        try {
            //刷新单条记录 刷新过程可能接收到新消息刷新 position 的位置就会有变动 有可能没刷对应到的position try一下
            List<EMMessage> allData = chatMessageAdapter.getAllData();
            for(int i=allData.size()-1;i>=0;i--){
                EMMessage emMessage = allData.get(i);
                if(emMessage.getMsgId().equals(msg.getMsgId())){
                    chatMessageAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    //消息接收--------------------------------------------------------------------------------end



    public static final int REQUEST_CALL_PERMISSION = 10111; //拨号请求码

    /**
     * 判断是否有某项权限
     * @param string_permission 权限
     * @param request_code 请求码
     * @return
     */
    public boolean checkReadPermission(String string_permission,int request_code) {
        boolean flag = false;
        if (ContextCompat.checkSelfPermission(this, string_permission) == PackageManager.PERMISSION_GRANTED) {//已有权限
            flag = true;
        } else {//申请权限
            ActivityCompat.requestPermissions(this, new String[]{string_permission}, request_code);
        }
        return flag;
    }

    /**
     * 检查权限后的回调
     * @param requestCode 请求码
     * @param permissions  权限
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CALL_PERMISSION: //拨打电话
                if (permissions.length != 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {//失败
                    Toast.makeText(this,"请允许拨号权限后再试", Toast.LENGTH_SHORT).show();
                } else {//成功
                    call("tel:"+"10086");
                }
                break;
        }
    }

    /**
     * 拨打电话（直接拨打）
     * @param telPhone 电话
     */
    public void call(String telPhone) {
        if (checkReadPermission(Manifest.permission.CALL_PHONE, REQUEST_CALL_PERMISSION)) {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+telPhone));
            startActivity(intent);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
